package com.shelpe.services.lexicon.service;

import java.io.IOException;
import java.util.ArrayList;
import java.util.Date;
import java.util.Iterator;
import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.shelpe.services.lexicon.constants.Origin;
import com.shelpe.services.lexicon.entity.AdgroupRecord;
import com.shelpe.services.lexicon.entity.KeywordRecommend;
import com.shelpe.services.lexicon.po.AutoProductQueue;
import com.shelpe.services.lexicon.repository.jpa.AutoProductQueueRepository;
import com.shelpe.services.lexicon.repository.mongo.KeywordRecommendRepository;

import lombok.extern.slf4j.Slf4j;

@Service
@Slf4j
public class ShelpeKeywordService {

	@Autowired
	private AutoProductQueueRepository autoProductQueueRepository;
	@Autowired
	private ObjectMapper objectMapper;
	@Autowired
	private KeywordRecommendRepository keywordRecommendRepository;
	
	public void syncKeywords(AdgroupRecord record){
		AutoProductQueue queue = this.autoProductQueueRepository.findByAdgroupIDAndUserID(record.getAdgroupID(), record.getTanentID());
		if(queue != null){
			String wordStr = queue.getCandWords();
			List<String> words = this.parseWords(wordStr);
			for(String word: words){
				KeywordRecommend kr = new KeywordRecommend();
				kr.setWord(word);
				kr.setCreateTime(new Date());
				kr.setLastModifiedTime(new Date());
				kr.setOrigin(Origin.shelpe);
				kr.setWeight(71);
				
				if(record != null){
					kr.setAdgroupID(record.getAdgroupID());
					kr.setAdgroupRecordID(record.getRecordID());
				}
				
				KeywordRecommend taobaoRec = this.keywordRecommendRepository.findByAdgroupIDAndOriginAndWord(record.getAdgroupID(), Origin.taobao, word);
				if(taobaoRec != null){
					kr.setMetric(taobaoRec.getMetric());
					kr.setPrice(taobaoRec.getPrice());
					kr.setPerformance(taobaoRec.getPerformance());
					kr.setPqr(taobaoRec.getPqr());
					log.debug("find tabao recommend word with same word: {}", word);
				}
				
				this.keywordRecommendRepository.save(kr);
			}
		}
	}
	
	private List<String> parseWords(String str){
		List<String> words = new ArrayList<String>();
		
		try {
			JsonNode root = this.objectMapper.reader().readTree(str);
			Iterator<String> it = root.fieldNames();
			while(it.hasNext()){
				words.add(it.next());
			}
		} catch (JsonProcessingException e) {
			log.error("JsonProcessingException: {}", e);
		} catch (IOException e) {
			log.error("IOException: {}", e);
		}
		
		
		return words;
	}
}
